/*******************************************************************************
 * 版权：北京润尼尔网络科技有限公司，保留所有版权<br>
 * 版本：v1.0.0<br>
 * 文件：AppContext.js<br>
 * 日期：2017年9月29日<br>
 * 作者: 样顺强<br>
 * 功能：应用程序入口对象<br>
 *
 * 修改记录：<br>
 * 日期 描述 更新功能<br>
 ******************************************************************************/

window.makeNamespace(window, "Rainier.UI.V2");

Rainier.UI.V2.AppContext = Rainier.Basic.CompositeObject.extend({
  NAME: "Rainier.UI.V2.AppContext",

  /**
   * 函数名称：init<br>
   * 函数功能：构造函数<br>
   * 参数信息：application:功能函数，
   * 异常信息：无<br>
   */
  init: function (application) {
    this._super();
    this.$container = null;
    this.activeEditor = null;
    this.boxEditor = null;
    this.application = application;
    this.partLib = "project";
    this.usedPartLib = "project_used";
    this.experConverter = new Rainier.UI.V2.ExperimentConverter();
    // this.webSocket	    = new Rainier.UI.V2.AppWebSocket();
    this.listeners = new draw2d.util.ArrayList();
    this.listeners.push(new Rainier.UI.V2.EditorObjectSelectionChangeListener());
    this.listeners.push(new Rainier.UI.V2.PartLibSelectionChangeListener());

    this.currentExperimentName = "";

    this.scrollLeft = 0;
    this.scrollTop = 0;

    //添加事件监听机制，处理返回计算引擎返回信息；
    // window.addEventListener("message", $.proxy(this.messageHandler, this));
  },

  /**
   * 函数名称：connectComputePlugin<br>
   * 函数功能：连接计算引擎插件<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  connectComputePlugin: function () {
    //启动websocket连接
    if (this.webSocket) {
      this.webSocket.connect();
      //定时检测(10s)是否断线 并添加重连功能。
      setInterval(
        $.proxy(function () {
          if (this.webSocket.getReadyState() !== 1) {
            this.webSocket.reconnect();
          }
        }, this),
        10000
      );
    }

    //初始化信息处理器
    this.webSocket.getMessageFactory().initMessage();
  },

  /**
   * 函数名称：getApplication<br>
   * 函数功能：获取应用对象<br>
   * 参数信息：无，
   * 返回信息：应用程序，
   * 异常信息：无<br>
   */
  getApplication: function () {
    return this.application;
  },

  /**
   * 函数名称：getActiveEditor<br>
   * 函数功能：设置应用程序编辑界面<br>
   * 参数信息：activeEditor : 获取当前编辑界面，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  setActiveEditor: function (activeEditor) {
    this.activeEditor = activeEditor;
  },

  /**
   * 函数名称：getActiveEditor<br>
   * 函数功能：获取应用程序编辑界面<br>
   * 参数信息：无，
   * 返回信息：当前编辑器，
   * 异常信息：无<br>
   */
  getActiveEditor: function () {
    return this.activeEditor;
  },

  /**
   * 函数名称：setBoxEditor<br>
   * 函数功能：设置方框图应用程序编辑界面<br>
   * 参数信息：activeEditor : 获取当前编辑界面，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  setBoxEditor: function (boxEditor) {
    this.boxEditor = boxEditor;
  },

  /**
   * 函数名称：getBoxEditor<br>
   * 函数功能：获取方框图应用程序编辑界面<br>
   * 参数信息：activeEditor : 获取当前编辑界面，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  getBoxEditor: function () {
    return this.boxEditor;
  },

  /**
   * 函数名称：setPartLib<br>
   * 函数功能：设置应用程序编辑界面<br>
   * 参数信息：无，
   * 返回信息：当前选中的实验，
   * 异常信息：无<br>
   */
  setPartLib: function (partLib) {
    this.partLib = partLib;
  },

  /**
   * 函数名称：getPartLib<br>
   * 函数功能：设置应用程序编辑界面<br>
   * 参数信息：无，
   * 返回信息：当前选中的实验，
   * 异常信息：无<br>
   */
  getPartLib: function () {
    return this.partLib;
  },

  /**
   * 函数名称：setUsedPartLib<br>
   * 函数功能：设置已使用的器材界面<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */

  setUsedPartLib: function (usedPartLib) {
    this.usedPartLib = usedPartLib;
  },

  /**
   * 函数名称：getUsedPartLib<br>
   * 函数功能：获取已使用的器材界面<br>
   * 参数信息：无，
   * 返回信息：已使用器材视图，
   * 异常信息：无<br>
   */
  getUsedPartLib: function () {
    return this.usedPartLib;
  },

  /**
   * 函数名称：getWebSocket<br>
   * 函数功能：获取socket连接<br>
   * 参数信息：无，
   * 返回信息：当前选中的实验，
   * 异常信息：无<br>
   */
  getWebSocket: function () {
    return this.webSocket;
  },

  /**
   * 函数名称：getEditorObjectSelectionChangeListener<br>
   * 函数功能：获取editor面板元件选中变化监听器<br>
   * 参数信息：无，
   * 返回信息：编辑器界面选中元件监听器，
   * 异常信息：无<br>
   */
  getEditorObjectSelectionChangeListener: function () {
    return this.listeners.get(0);
  },

  /**
   * 函数名称：getPartLibSelectionChangeListener<br>
   * 函数功能：获取元件库选中改变监听器<br>
   * 参数信息：无，
   * 返回信息：partLib界面选中元件监听器，
   * 异常信息：无<br>
   */
  getPartLibSelectionChangeListener: function () {
    return this.listeners.get(1);
  },

  /**
   * 函数名称：getCurrentExperimentName<br>
   * 函数功能：获取实验凭条当前名字<br>
   * 参数信息：无，
   * 返回信息：partLib界面选中元件监听器，
   * 异常信息：无<br>
   */
  getCurrentExperimentName: function () {
    return this.currentExperimentName;
  },

  /**
   * 函数名称：setCurrentExperimentName<br>
   * 函数功能：设置实验平台当前实验名字<br>
   * 参数信息：无，
   * 返回信息：partLib界面选中元件监听器，
   * 异常信息：无<br>
   */
  setCurrentExperimentName: function (expName) {
    this.currentExperimentName = expName;
  },

  /**
   * 函数名称：commandToCopy<br>
   * 函数功能：复制元件<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  commandToCopy: function () {
    //暂不做处理
    console.log("copy");
  },

  /**
   * 函数名称：commandToCut<br>
   * 函数功能：剪切元件<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  commandToCut: function () {
    //暂不做处理
    console.log("cut");
  },

  /**
   * 函数名称：commandToPaste<br>
   * 函数功能：粘贴元件<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  commandToPaste: function () {
    //暂不做处理
    console.log("paste");
  },
  /**
   * 函数名称：Rainier.UI.V2.CanvasMenu.clearTable<br>
   * 函数功能：清空试验台<br>
   * 参数输入：无<br>
   * 参数输出：无<br>
   * 函数返回：无<br>
   * 异常信息：无<br>
   */
  clearTable: function () {
    var _this = this;
    var activeEditor = window.app.getContext().getActiveEditor();
    var rootEditPart = activeEditor.rootEditPart;
    var canvas = rootEditPart.figure;
    var figures = canvas.getFigures();
    canvas.getCommandStack().startTransaction(draw2d.Configuration.i18n.command.deleteShape);
    figures.each(function (index, figure) {
      var cmd = figure.createCommand(new draw2d.command.CommandType(draw2d.command.CommandType.DELETE));
      if (cmd !== null) {
        canvas.getCommandStack().execute(cmd);
      }
    });
    // execute all single commands at once.
    canvas.getCommandStack().commitTransaction();
    this.tabId = app.canvasId;
    hideImgArr[this.tabId] = [];
  },
  /**
   * 函数名称：commandTodelete<br>
   * 函数功能：删除元件<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  commandToDelete: function () {
    var activeEditor = window.app.getContext().getActiveEditor();
    var rootEditPart = activeEditor.rootEditPart;
    var canvas = rootEditPart.figure;
    var figures = canvas.getSelection().all;
    canvas.getCommandStack().startTransaction(draw2d.Configuration.i18n.command.deleteShape);
    figures.each(function (index, figure) {
      var cmd = figure.createCommand(new draw2d.command.CommandType(draw2d.command.CommandType.DELETE));
      if (cmd !== null) {
        canvas.getCommandStack().execute(cmd);
      }
    });
    // execute all single commands at once.
    canvas.getCommandStack().commitTransaction();
  },

  /**
   * 函数名称：commandToRedo<br>
   * 函数功能：恢复撤销的内容<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  commandToRedo: function () {
    var activeEditor = window.app.getContext().getActiveEditor();
    var rootEditPart = activeEditor.rootEditPart;
    var canvas = rootEditPart.figure;
    canvas.getCommandStack().redo();
  },

  /**
   * 函数名称：commandToUndo<br>
   * 函数功能：撤销上一步操作<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  commandToUndo: function () {
    var activeEditor = window.app.getContext().getActiveEditor();
    var rootEditPart = activeEditor.rootEditPart;
    var canvas = rootEditPart.figure;
    canvas.getCommandStack().undo();
  },

  /**
   * 函数名称：commandToSave<br>
   * 函数功能：保存实验<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  commandToSave: function () {
    console.log("save");
    //测试平台提交时数据格式
    // var xmlString = this.uploadExperiment();
    // this.messageHandler({ data: xmlString });
    // console.log(xmlString);
    // return;
    var _this = this;
    var hideImgId = {};
    var keys = Object.keys(hideImgArr);
    $.each(keys, function (index, key) {
      var idArr = [];
      $.each(hideImgArr[key], function (i, deleteInfo) {
        var id = deleteInfo.model.m_sUuid;
        idArr.push(id);
      });
      hideImgId[key] = idArr;
    });
    // 先显示隐藏的图片

    idArray.forEach((item) => {
      app = appObj[item.id];
      var canvas = app.context.activeEditor.rootEditPart.figure;
      cmd = new Rainier.UI.V2.CommandShowAllImg(canvas.context);
      canvas.getCommandStack().execute(cmd);
    });

    var random = new Date().getTime();
    var name = this.currentExperimentName ? this.currentExperimentName : "design_" + random;
    var rootNode = $("#ul-mindMap").tree("find", "firstPage");
    var treeData = $("#ul-mindMap").tree("getData", rootNode.target);
    var treeDatas = Object.assign({}, treeData);
    this.deleteData(treeDatas);
    if (name) {
      idArray.forEach((item) => {
        var id = item.id;
        window.app = appObj[id];
        // _this.activeEditor = window.app.getContext().getActiveEditor();
        // var json    = _this.activeEditor.doSaveAs(name);
        var a = window.app.getContext().getActiveEditor();
        // _this.activeEditor =
        var json = a.doSaveAs(name);
        if (id == "firstPage") {
          var canvasJson = {};
          canvasJson.tabTitle = "首页";
          canvasJson.json = json;
          //保存树结构数据
          canvasJson.treeData = Object.assign({}, treeDatas);
          //保存隐藏的图片
          canvasJson.hideImgId = hideImgId;
          appJson[id] = canvasJson;
        } else {
          var canvasJson = {};
          canvasJson.tabTitle = item.tabTitle;
          canvasJson.json = json;
          //保存隐藏的图片
          canvasJson.hideImgId = hideImgId;
          appJson[id] = canvasJson;
        }
      });
      var jsonString = JSON.stringify(appJson, null, 4);
      var file = new File([jsonString], name + ".ocj", {
        type: "text/plain;charset=utf-8",
      });
      saveAs(file);
    }
    //重新隐藏图片
    // $.each(idArray,function(index,id){
    // 	app = appObj[id];
    // 	var canvas = app.context.activeEditor.rootEditPart.figure;
    // 	canvas.getCommandStack().undo();
    // 	var redostack = canvas.getCommandStack().redostack;
    // 	redostack.splice(redostack.length-2,1);
    // });
  },

  /**
   * @名称   onClickCancel
   * @功能   删除树结构数据中多余数据
   * @author 孙燕宝
   * @data   2018-08-23
   * @return {[type]}   [description]
   */
  deleteData: function (data) {
    delete data.target;
    delete data.domId;
    var children = data.children;
    var _this = this;
    if (children) {
      $.each(children, function (key, child) {
        _this.deleteData(child);
      });
    }
  },

  /**
   * 函数名称：commandToSaveAs<br>
   * 函数功能：另存为实验<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  commandToSaveAs: function () {
    var random = new Date().getTime();
    var name = this.currentExperimentName ? this.currentExperimentName : "design_" + random;
    new Rainier.UI.V2.SaveAsExperimentDialog(name);
  },

  /**
   * 函数名称：commandToOpen<br>
   * 函数功能：打开新实验<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  commandToOpen: function () {
    new Rainier.UI.V2.OpenExprimentDialog();
  },

  /**
   * 函数名称：commandToFullScreen<br>
   * 函数功能：实验平台全屏显示<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  commandToFullScreen: function () {
    var $fullScreen = $("#full_screen");
    var $fullScreenTitle = $fullScreen.attr("title");
    if ($fullScreenTitle == "全屏") {
      $fullScreen.children("a").removeClass("fullScreenImg");
      $fullScreen.children("a").addClass("leaveFullScreenImg");
      $fullScreen.attr("title", "退出全屏");
      this.enterFullScreen();
    }
    if ($fullScreenTitle == "退出全屏") {
      $fullScreen.children("a").addClass("fullScreenImg");
      $fullScreen.children("a").removeClass("leaveFullScreenImg");
      $fullScreen.attr("title", "全屏");
      this.exitFullScreen();
    }
  },

  /**
   * 函数名称：commandToZoomRestore<br>
   * 函数功能：实验台缩放和还原<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  commandToZoomRestore: function () {
    var $zoomRestore = $("#zoom_restore");
    var $zoomRestoreTitle = $zoomRestore.attr("title");
    if ($zoomRestoreTitle == "全览") {
      $zoomRestore.children("a").removeClass("zoomImg");
      $zoomRestore.children("a").addClass("restoreImg");
      $zoomRestore.attr("title", "还原");
      this.zoomExp();
    }
    if ($zoomRestoreTitle == "还原") {
      $zoomRestore.children("a").removeClass("restoreImg");
      $zoomRestore.children("a").addClass("zoomImg");
      $zoomRestore.attr("title", "全览");
      this.restoreExp();
    }
  },

  /**
   * 函数名称：zoomExp<br>
   * 函数功能：实验平台全览<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  zoomExp: function () {
    var activeEditor = this.getActiveEditor();
    var canvas = activeEditor.canvas;
    canvas.setZoom(10.0, true);
    // console.log(canvas);
    var canvasHtmlContainer = canvas.getHtmlContainer();
    var canvasParent = canvasHtmlContainer.parent().parent();
    this.scrollLeft = canvasParent[0].scrollLeft;
    this.scrollTop = canvasParent[0].scrollTop;
    // canvasParent[0].scrollTo(0, 0);
  },

  /**
   * 函数名称：restoreExp<br>
   * 函数功能：还原实验台<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  restoreExp: function () {
    var activeEditor = this.getActiveEditor();
    var canvas = activeEditor.canvas;
    canvas.setZoom(1.0, true);
    var canvasHtmlContainer = canvas.getHtmlContainer();
    var canvasParent = canvasHtmlContainer.parent().parent();
    // canvasParent[0].scrollTo(this.scrollLeft, this.scrollTop);
  },

  /**
   * 函数名称：checkFull<br>
   * 函数功能：判断是否全屏<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  checkFull: function () {
    var isFull =
      document.fullscreenEnabled || window.fullScreen || document.webkitIsFullScreen || document.msFullscreenEnabled;

    //to fix : false || undefined == undefined
    if (isFull === undefined) isFull = false;
    return isFull;
  },

  /**
   * 函数名称：enterFullScreen<br>
   * 函数功能：实验平台全屏显示<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  enterFullScreen: function () {
    var element = $("body")[0];
    var requestMethod =
      element.requestFullScreen ||
      element.webkitRequestFullScreen ||
      element.mozRequestFullScreen ||
      element.msRequestFullScreen;
    if (requestMethod) {
      requestMethod.call(element);
    }
  },
  /**
   * 函数名称：exitFullScreen<br>
   * 函数功能：实验平台退出全屏<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  exitFullScreen: function () {
    var el = document;
    var cfs = el.cancelFullScreen || el.webkitCancelFullScreen || el.mozCancelFullScreen || el.exitFullScreen;
    if (typeof cfs != "undefined" && cfs) {
      cfs.call(el);
    } else if (typeof window.ActiveXObject != "undefined") {
      //for IE，这里和fullScreen相同，模拟按下F11键退出全屏
      var wscript = new ActiveXObject("WScript.Shell");
      if (wscript != null) {
        wscript.SendKeys("{F11}");
      }
    }
  },
  /**
   * 函数名称：init<br>
   * 函数功能：恢复原实验平台大小<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  commandToFitScreen: function () {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen();
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen();
    } else if (document.oRequestFullscreen) {
      document.oCancelFullScreen();
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen();
    }
  },

  /**
   * 函数名称：commandToUploadPicture<br>
   * 函数功能：上传图片<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  commandToUploadPicture: function () {
    // 向网络发送上传图片的消息
    new Rainier.UI.V2.UploadExpPictureDialog();
  },

  //界面运行逻辑
  /**
   * 函数名称：clickToControlExperiment<br>
   * 函数功能：点击控制实验列表状态<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  clickToControlExperiment: function () {},

  /**
   * 函数名称：clickToControlPartLib<br>
   * 函数功能：点击控制元件库状态<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  clickToControlPartLib: function (flag) {
    var partLibComponent = this.application.getPartLibComponent();
    var usedPartLibComponent = this.application.getUsedPartLibComponent();
    if (flag) {
      partLibComponent.clickToHide();
      usedPartLibComponent.clickToShow();
    } else {
      partLibComponent.clickToShow();
      usedPartLibComponent.clickToHide();
    }
  },

  /**
   * 函数名称：clickToControlZoom<br>
   * 函数功能：点击控制元件库状态<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  clickToControlZoom: function (flag) {
    var activeEditor = this.getActiveEditor();
    var canvas = activeEditor.canvas;
    if (flag) {
      canvas.setZoom(10.0, true);
    } else {
      canvas.setZoom(1.0, true);
    }
  },

  /**
   * 函数名称：clickToControlAnalyse<br>
   * 函数功能：点击控制实验仿真类型<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  clickToControlAnalyse: function (flag) {
    new Rainier.UI.V2.InteractiveAnalysisDialog();
  },
  /**
   * 函数名称：clickToControlResult<br>
   * 函数功能：点击控制实验结果类型<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  clickToControlResult: function (flag) {
    var eastLayoutPanel = $("#app").layout("panel", "east")[0].clientWidth;
    if (eastLayoutPanel > 0) {
      $("#app").layout("collapse", "east");
    } else {
      $("#app").layout("expand", "east");
    }
  },
  /**
   * 函数名称：clickToControlResultUpdata<br>
   * 函数功能：点击实验结果面板展开和收缩按钮控制实验结果图片的替换<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  clickToControlResultUpdata: function () {
    var getResultElement = $(".app-control li").eq(1).children("a");
    var resultStates = getResultElement.hasClass("app-control-btn-result");
    if (resultStates) {
      getResultElement.removeClass("app-control-btn-result").addClass("app-control-btn-result-on");
      getResultElement.data("flag", true);
    } else {
      getResultElement.removeClass("app-control-btn-result-on").addClass("app-control-btn-result");
      getResultElement.data("flag", false);
    }
  },
  /**
   * 函数名称：clickToControlRunState<br>
   * 函数功能：点击控制当前实验运行状态<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  clickToControlRunState: function () {
    console.log("运行实验");
    //关闭当前平台打开的对话框；
    var dialogs = this.application.dialogList ? this.application.dialogList : null;
    if (dialogs && dialogs.getSize()) {
      while (dialogs.getSize() > 0) {
        dialogs.get(0).dialog.close(true);
        dialogs.data.splice(0, 1);
      }
    }
    var editor = this.getActiveEditor();
    var webSocket = this.getWebSocket();
    if (editor && editor instanceof Rainier.UI.V2.Draw2dGraphicalEditor) {
      var context = editor.context;
      var parser = context.getCircuitParser();
      if (parser) {
        parser.parse(true);
        //第一步：生成spice语句
        // if(context.experimentCfg){
        // 	sSpice = parser.makeSpice(parser.getSpice());
        // }else{
        // 	sSpice = parser.addControlSpice(parser.getSpice());
        // }

        if (webSocket) {
          //应对 专家评审时，开一个结算引擎，电路和通信之间进行切换bug
          var msgInfoPause = {
            needReturn: 1,
            type: USER_CMD_MSG,
            msg: USER_CMD_MSG_PAUSE,
            engineId: "ngspice",
          };
          var msgInfoStop = {
            needReturn: 1,
            type: USER_CMD_MSG,
            msg: USER_CMD_MSG_STOP,
            engineId: "ngspice",
          };
          webSocket.sendMsgByInfo(msgInfoPause);
          webSocket.sendMsgByInfo(msgInfoStop);

          var msgInfoScene = {
            needReturn: 1,
            type: USER_SCENE_MSG,
            msg: parser.getSpice(),
            engineId: "octave",
          };
          var msgInfoRun = {
            needReturn: 1,
            type: USER_CMD_MSG,
            msg: USER_CMD_MSG_RUN,
            engineId: "octave",
          };
          webSocket.sendMsgByInfo(msgInfoScene);
          webSocket.sendMsgByInfo(msgInfoRun);

          //保存运行态编辑器到context
          //editor.enterRunStatus();
          editor.rootEditPart.exitCreateState();

          if (webSocket) {
            var messageHandlerList = webSocket.getMessageFactory().messageHandlerList;
            var messageHandler = messageHandlerList[CMS_ENGIN_RESULT];
            if (messageHandler) {
              var rootModel = editor.context.getRootModel();
              messageHandler.addPropertyListener("propertyListener", rootModel);
            }
          }
        }
      }
    }
  },

  /**
   * 函数名称：clickToControlRunState<br>
   * 函数功能：点击控制当前实验运行状态<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  clickToControlPauseState: function () {
    console.log("暂停实验");

    var socket = this.getWebSocket();
    var editor = this.getActiveEditor();
    if (socket) {
      var msgInfoPause = {
        needReturn: 1,
        type: USER_CMD_MSG,
        msg: USER_CMD_MSG_PAUSE,
      };
      socket.sendMsgByInfo(msgInfoPause);

      //退出运行状态；
      editor.leaveRunStatus();

      var messageHandlerList = socket.getMessageFactory().messageHandlerList;
      var messageHandler = messageHandlerList[CMS_ENGIN_RESULT];
      if (messageHandler) {
        messageHandler.clearPropertyListener();
      }
    }
  },
  /**
   * 函数名称：clickToControlRunState<br>
   * 函数功能：点击控制当前实验运行状态<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  clickToControlstopState: function () {
    console.log("停止实验");
    var socket = this.getWebSocket();
    var editor = this.getActiveEditor();
    if (socket && editor) {
      var msgInfoPause = {
        needReturn: 1,
        type: USER_CMD_MSG,
        msg: USER_CMD_MSG_PAUSE,
      };
      var msgInfoStop = {
        needReturn: 1,
        type: USER_CMD_MSG,
        msg: USER_CMD_MSG_STOP,
      };
      socket.sendMsgByInfo(msgInfoPause);
      socket.sendMsgByInfo(msgInfoStop);

      //退出运行状态
      editor.leaveRunStatus();

      var messageHandlerList = socket.getMessageFactory().messageHandlerList;
      var messageHandler = messageHandlerList[CMS_ENGIN_RESULT];
      if (messageHandler) {
        messageHandler.clearPropertyListener();
      }
    }
  },

  /**
   * [restartParse description]
   * @param  {[type]} content [description]
   * @return {[type]}         [description]
   */
  restartParse: function (content) {
    if (this.getActiveEditor().runStatus) {
      //第一步：暂停当前实验
      this.clickToControlstopState();
      //第二步：启动当前实验
      this.clickToControlRunState(true);
    }
  },

  /**
   * 函数名称：clickToAnalyticalResults<br>
   * 函数功能：点击控制实验变量状态<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  clickToAnalyticalResults: function (flag) {
    var expermentalResult = this.application.getResultComponent();
    expermentalResult.collapse();
    expermentalResult.clear();
    expermentalResult.clickTohide();
  },
  /**
   * 函数名称：runExperiment<br>
   * 函数功能：手动启动实验<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  runExperiment: function () {
    $(".app-run").click();
  },

  /**
   * 函数名称：controlAnalyse<br>
   * 函数功能：控制仿真分析的状态<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  controlAnalyse: function () {
    $(".app-analyse").click();
  },

  /**
   * 函数名称：<br>
   * 函数功能：websocket发送消息<br>
   * 参数输入：<br>
   * 参数输出：<br>
   * 函数返回：<br>
   * 异常信息：<br>
   */
  uploadExperiment: function () {
    var _this = this;
    var hideImgId = {};
    var keys = Object.keys(hideImgArr);
    $.each(keys, function (index, key) {
      var idArr = [];
      $.each(hideImgArr[key], function (i, deleteInfo) {
        var id = deleteInfo.model.m_sUuid;
        idArr.push(id);
      });
      hideImgId[key] = idArr;
    });
    // 先显示隐藏的图片
    idArray.forEach((item) => {
      app = appObj[item.id];
      var canvas = app.context.activeEditor.rootEditPart.figure;
      cmd = new Rainier.UI.V2.CommandShowAllImg(canvas.context);
      canvas.getCommandStack().execute(cmd);
    });
    idArray.forEach((item) => {
      var id = item.id;
      window.app = appObj[id];
      var activeEditor = window.app.getContext().getActiveEditor();
      var exper = activeEditor.doSave();
      //保存树结构
      var rootNode = $("#ul-mindMap").tree("find", "firstPage");
      var treeData = $("#ul-mindMap").tree("getData", rootNode.target);
      var treeDatas = Object.assign({}, treeData);
      _this.deleteData(treeDatas);
      if (id == "firstPage") {
        exper.tabTitle = "首页";
        exper.tabId = "firstPage";
        //保存树结构数据
        if (treeDatas.children) {
          if (treeDatas.children && treeDatas.id == treeDatas.children[0].children[0].id) {
            treeDatas = { ...treeDatas.children[0] };
          }

          exper.treeData = treeDatas;
          console.log("首页有孩子" + exper.treeDatas);
        } else {
          exper.treeData = treeDatas;
          console.log("首页无孩子" + exper.treeDatas);
        }
        //保存隐藏的图片
        exper.hideImgId = hideImgId;
        appExper[id] = exper;
      } else {
        exper.tabTitle = item.tabTitle;
        exper.tabId = id;
        //保存隐藏的图片
        exper.hideImgId = hideImgId;
        appExper[id] = exper;

        // $.each(tabs, function (index, tab) {
        //   var tempId = tab.panel('options').id;
        //   if (tempId == id) {
        //     var tempTitle = tab.panel('options').title;
        //     exper.tabTitle = tempTitle;
        //     exper.tabId = tempId;
        //     //保存隐藏的图片
        //     exper.hideImgId = hideImgId;
        //     appExper[id] = exper;
        //   }
        // });
      }
    });
    var xmlString = this.experConverter.convertExperToXml(appExper);
    console.log("xmlString", xmlString);
    //重新隐藏图片
    idArray.forEach((item) => {
      app = appObj[item.id];
      var canvas = app.context.activeEditor.rootEditPart.figure;
      canvas.getCommandStack().undo();
      var redostack = canvas.getCommandStack().redostack;
      redostack.splice(redostack.length - 2, 1);
    });
    if (xmlString.indexOf("<intellcorrect>") >= 0) {
      var scriptVal = xmlString;
      openExper = true;
      if (scriptVal) {
        var xmlDoc; //XMLDocument
        var experObject;
        xmlDoc = $.parseXML(scriptVal);
        if (xmlDoc) {
          var tabId = $(xmlDoc).find("tabId").text();
          var tabIdArray = tabId.split("id");
          $.each(tabIdArray, function (index, id) {
            if (id !== "") {
              var exper = "exper" + id;
              var experString = decodeURIComponent(escape(window.atob($(xmlDoc).find(exper).text())));
              experObject = JSON.parse(experString);

              //恢复树结构
              if (experObject.treeData != undefined && experObject.treeData.children != undefined) {
                var treeData = experObject.treeData;
                if (treeData) {
                  var data = [];
                  console.log("回显实验内容:" + treeData);
                  data.push(treeData);
                  setTimeout(() => {
                    $("#ul-mindMap").tree("loadData", data);
                    openExper = false;
                  }, 1);
                }
              }
            }
          });
        }
      }
    }
    return xmlString;
  },

  /**
   * 函数名称：messageHandler<br>
   * 函数功能：处理websocket返回数据<br>
   * 参数信息：无，
   * 返回信息：无，
   * 异常信息：无<br>
   */
  messageHandler: function (event) {
    //父页面请求保存当前实验
    if (event.data === "uploadExperiment") {
      var json = this.uploadExperiment();
      parent.postMessage(json, "*");
    }
    //父页面请求打开实验
    else if (event.data.indexOf("<intellcorrect>") >= 0) {
      var scriptVal = event.data;
      openExper = true;
      if (scriptVal) {
        var xmlDoc; //XMLDocument
        var experObject;
        xmlDoc = $.parseXML(scriptVal);
        if (xmlDoc) {
          var tabId = $(xmlDoc).find("tabId").text();
          var tabIdArray = tabId.split("id");
          $.each(tabIdArray, function (index, id) {
            var exper = "exper" + id;
            var experString = decodeURIComponent(escape(window.atob($(xmlDoc).find(exper).text())));
            experObject = JSON.parse(experString);
            //只打开首页的tab界面
            if (id == "firstPage") {
              //恢复实验前打开tab页
              var appTabComponent = new Rainier.UI.V2.AppTabComponent();
              var title = experObject.tabTitle;
              appTabComponent.openTab(id, title);
              app = appObj[id];
              var editor = app.getContext().getActiveEditor();
              if (editor) {
                editor.doRestore(experObject);
              }

              //恢复隐藏图片库
              window.hideImgArr = {};
              var hideImgId = experObject.hideImgId;
              var keys = Object.keys(hideImgId);
              $.each(keys, function (index, key) {
                var idArr = [];
                if (key == "#FirstPage") {
                  window.app = appObj["firstPage"];
                } else {
                  window.app = appObj[key.substring(11)];
                }
                $.each(hideImgId[key], function (i, id) {
                  var rootModel = window.app.context.activeEditor.context.getRootModel();
                  var model = _this.getModelById(rootModel, id);
                  var deleteInfo = rootModel.removeChildModel(model);
                  idArr.push(deleteInfo);
                });
                hideImgArr[key] = idArr;
              });

              //恢复树结构
              var treeData = experObject.treeData;
              if (treeData) {
                var data = [];
                // console.log("回显实验内容:" + treeData);
                data.push(treeData);
                setTimeout(() => {
                  $("#ul-mindMap").tree("loadData", data);
                  openExper = false;
                }, 1);
              }
            } else {
              //暂存子实验的json数据
              expActiveJsonObj[id] = experObject;
            }
          });
        }
      }
    }
  },
});
var appExper = {};
